#!/usr/bin/perl
#
# replicate
#
# Replicate the directory structure of a remote site
# in the specified directory on the local system.
#
# This script can be freely distributed and used freely
# as long as this copyright notice is preserved. The
# script can be modified as required, as long as this
# copyright notice is preserved.
#
#
# The script gets the names of the files to download, from
# the file "list.txt". Each of the files mentioned in the
# list is downloaded to the destination directory. The
# directory hierarchy of the source is maintained in the
# destination directory.
#
# Released under Apache License, Version 2.0.
#

# use the FTP package
use Net::FTP;
use Getopt::Long;

# get command line parameters
GetOptions (
	"source=s" => \$source, "s=s" => \$source,
	"user=s" => \$user, "u=s" => \$user,
	"pass=s" => \$pass, "p=s" => \$pass,
	"local=s" => \$localdir, "l=s" => \$localdir,
	"remote=s" => \$remotedir, "r=s" => \$remotedir,
	"files=s" => \$listing, "f=s" => \$listing
);

if ( $help ) {
	print "replicate.pl [--source|-s server] "
			. "[--user|u user] [--pass|-u password] "
			. "[--local|-l local-dir] [--remote|-r remote-dir] "
			. "[--files|-f file-list]\n";
}

# assign default values if command line params not provided
if ( !$source ) {
	$source = "127.0.0.1";
}
if ( !$user ) {
	$user = "guest";
}
if ( !$pass ) {
	$pass = "guest123";
}
if ( !$listing ) {
	$listing = "list.txt";
}
if ( !$localdir ) {
	$localdir = ".";
}

# connect to the site
$ftp = Net::FTP->new($source, Debug => 0)
			or die "Cannot connect to $source: $@";
# login
$ftp->login($user, $pass);

# if remote dir not specified, use the login dir
if ( !$remotedir ) {
	$remotedir = $ftp->pwd();
}

# open the list of files
open (LIST, "<" . $listing);

while ( <LIST> ) {
	chomp($_); # eat the newline
	@dirs = split(/\//, $_); # split on '/', to get dir names
	$dircount = @dirs;

	# Make the directory structure on the destination
	# similar to that on the source.
	#
	# IMP Last name in the path is assumed to be name of
	# the file.
	$idx = 0;
	$dest = $localdir;
	while ( $idx < $dircount - 1 ) {
		$dest = $dest . "/" . $dirs[$idx];
		mkdir($dest);
		$idx++;
	}

	# get filename
	$final = $dirs[$idx];
	# construct full destination path
	$dest = $dest . "/" . $final; 

	# remote filename
	$remotefile = $remotedir . "/" . $_;

	# download file
	print $remotefile . " > " . $dest . "\n";
	$ftp->get($remotefile, $dest) or print "Error: " . $ftp->message;
}

close (LIST);

# close ftp session
$ftp->quit;

exit 0;

#
# end
#
